﻿using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;

using HttpClientStudy.Model;
using HttpClientStudy.WebApp.Models;

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace HttpClientStudy.WebApp.Controllers
{
    /// <summary>
    /// 账号控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        /// <summary>
        /// 构造
        /// </summary>
        public AccountController() { }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public IActionResult GetToken(string userName, string password)
        {
            var account = new Account() { Id = 1, Name = userName, Password = password, Role = "Admin" };

            var principal = CreateClaimsPrincipal(account);
            var token = CreateJwtToken(principal.Claims.ToList());

            var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token };

            var result = BaseResultUtil.Success(data);
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult GetToken(LoginAccount vm)
        {
            var account = new Account() { Id = 1, Name = vm.Account, Password = vm.Password, Role = "Admin" };

            var principal = CreateClaimsPrincipal(account);
            var token = CreateJwtToken(principal.Claims.ToList());

            var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token };

            var result = BaseResultUtil.Success(data);
            return new JsonResult(result);
        }

        /// <summary>
        /// 生成ClaimsPrincipal
        /// </summary>
        private ClaimsPrincipal CreateClaimsPrincipal(Account account)
        {
            List<Claim> claims = new List<Claim>
            {
                 new Claim("ID", account.Id.ToString()),
                 new Claim("Name",account.Name??""),
                 new Claim("Password", account.Password??"123123"),
                 new Claim("Role",account.Role),
             };

            ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            return principal;
        }

        /// <summary>
        /// 生成JwtToken
        /// </summary>
        private string CreateJwtToken(List<Claim> claims)
        {
            //生成Jwt
            //jwtTokenOptions 是通过配置获取上面配置的参数信息
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0123456789abcdefghigklmnopqrstdf41sadfweqtdfghsdfgsdfweqr"));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //令牌
            var expires = DateTime.Now.AddDays(1);
            var token = new JwtSecurityToken
            (
                issuer: "WWW.WANGGAOFENG.CN",
                audience: "WWW.WANGGAOFENG.CN",
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: credentials
            );
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return jwtToken;
        }
    }
}
